package com.aidansmeaton.weightmanager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aidansmeaton.weightmanager.data.RedditPost;

/** The first activity in the app. */
public class RedditActivity extends ListActivity implements OnItemClickListener {

	private List<RedditPost> posts;
	private RedditAdapter adapter;	
	private String subreddit;
	private String message;

	private Context context;
	private RelativeLayout list;
	private ProgressBar progress;
	private TextView messageText;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reddit);
		
		context = this;
		posts = new ArrayList<RedditPost>();
		subreddit = this.getIntent().getExtras().getString("/r");
		message = this.getIntent().getExtras().getString("Message");
		list = (RelativeLayout) findViewById(R.id.list);
		progress = (ProgressBar) findViewById(R.id.progress);
		messageText = (TextView) findViewById(R.id.message);		
		
		DownloadPostsTask downloadTask = new DownloadPostsTask();
		downloadTask.execute(0);

	}
	
	public void linkClick(View v){
		String link = (String) v.getTag();
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
		startActivity(browserIntent);
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		RedditPost post = posts.get(position);
		String data = "<html><body>";
		data += Html.fromHtml(post.getDescription());
		data += "</body></html>";
		
		Intent postIntent = new Intent(RedditActivity.this, RedditPostActivity.class);
		postIntent.putExtra("Title", post.getTitle());
		postIntent.putExtra("Date", post.getDate());
		postIntent.putExtra("Link", post.getLink().toString());
		postIntent.putExtra("Description", data);		
		startActivity(postIntent);
		
    }

	private void downloadPosts() {

		String htmlResult = "";
		InputStream is = null;

		// http post
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://www.reddit.com/r/"+subreddit+".xml");
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}
		// convert response to string
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			is.close();

			htmlResult = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		while (htmlResult.contains("<item>")) {
			int itemStart = htmlResult.indexOf("<item>");
			int itemEnd = htmlResult.indexOf("</item>");

			String item = htmlResult.substring(itemStart, itemEnd + 7);

			String title = parseNextToken(item, "<title>", "</title>");
			String link = parseNextToken(item, "<link>", "</link>");
			String date = parseNextToken(item, "<pubDate>", "</pubDate>");
			String description = parseNextToken(item, "<description>", "</description>");

			URL linkURL = null;
			try {
				linkURL = new URL(link);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}

			RedditPost post = new RedditPost(title, linkURL, date, description);
			posts.add(post);
			htmlResult = htmlResult.substring(itemEnd + 7, htmlResult.length());
			Log.w("",""+htmlResult.length());
		}
	}

	private String parseNextToken(String fullText, String prefix, String suffix) {

		int itemStart = fullText.indexOf(prefix);
		int itemEnd = fullText.indexOf(suffix);

		return fullText.substring(itemStart + prefix.length(), itemEnd);
	}

	private class RedditAdapter extends ArrayAdapter<RedditPost> {

		private List<RedditPost> posts;

		public RedditAdapter(Context context, int textViewResourceId,
				List<RedditPost> posts) {
			super(context, textViewResourceId, posts);
			this.posts = posts;
		}

		@Override
		public int getCount() {
			return posts.size();
		}

		@Override
		public RedditPost getItem(int position) {
			return posts.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.reddit_row, null);
			}

			TextView titleTextView = (TextView) convertView.findViewById(R.id.reddit_row_title);
			TextView timeTextView = (TextView) convertView.findViewById(R.id.reddit_row_time);
			ImageView link = (ImageView) convertView.findViewById(R.id.link);
			
			RedditPost post = posts.get(position);
			
			convertView.setTag(R.id.reddit_post, post);
			titleTextView.setText(Html.fromHtml(post.getTitle()));
			timeTextView.setText(post.getDate());
			link.setTag(post.getLink().toString());
			
			return convertView;
		}
	}
	
	
	/* AsyncTask to download posts. */
	private class DownloadPostsTask extends AsyncTask<Integer, Integer, Boolean> {
		
		@Override
		protected void onPreExecute() {
			list.setVisibility(View.GONE);
			progress.setVisibility(View.VISIBLE);
			messageText.setVisibility(View.VISIBLE);
			messageText.setText(message);
		}
		
		@Override
		protected Boolean doInBackground(Integer... args) {
			downloadPosts();
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			adapter = new RedditAdapter(RedditActivity.this, R.layout.reddit_row, posts);
			setListAdapter(adapter);
			getListView().setOnItemClickListener(RedditActivity.this);
			list.setVisibility(View.VISIBLE);
			progress.setVisibility(View.GONE);
			messageText.setVisibility(View.GONE);
		}
	}
}